import 'dart:io';

import 'package:activity_record/model/data_base.dart';
import 'package:activity_record/model/diy.dart';
import 'package:activity_record/model/diy_image.dart';
import 'package:activity_record/model/diy_project.dart';
import 'package:activity_record/my_flutter_app_icons.dart';
import 'package:activity_record/pages/cloud_firebase.dart';
import 'package:activity_record/pages/diy_add_dialog.dart';
import 'package:activity_record/pages/diy_analysis.dart';
import 'package:activity_record/pages/diy_item_info.dart';
import 'package:activity_record/pages/diy_search.dart';
import 'package:activity_record/pages/fire_storage.dat.dart';
import 'package:activity_record/ui/diy_row.dart';
//import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
//import 'package:transparent_image/transparent_image.dart';
import 'package:activity_record/ui/diamond_fab.dart';
// import 'package:path_provider/path_provider.dart';
//import 'package:flutter_search_bar/flutter_search_bar.dart';
//import 'package:firebase_storage/firebase_storage.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:path_provider/path_provider.dart';

/*
这是首页，包含标题栏、底部导航栏和浮动按钮
因为
 */

class DiyHome extends StatefulWidget {
  final DataBase db;
  // final ValueChanged<bool> valueChanged;
  // final FirebaseStorage storage;
  // final Firestore fireStore;
  DiyHome({this.db});

  @override
  DiyHomeState createState() => new DiyHomeState(this.db);
}

class DiyHomeState extends State<DiyHome> with SingleTickerProviderStateMixin {
  DiyHomeState(this._database);
  DataBase _database;
  List<Diy> _diys = <Diy>[];
  //实例化diyProjects数组，并初始化空
  List<DiyProject> _diyProjects = <DiyProject>[];
  List<DiyImage> _diyImages = <DiyImage>[];
  List _everyDiyImages = [];
  //实例化没有结款的diyProject数组，同样初始化空
  // List<Diy> _unCheckedDiys = <Diy>[];
  //实例化diyProjects数组，并初始化空
  // List<DiyProject> _unCheckedDiyProjects = <DiyProject>[];
  // List<DiyImage> _unCheckedDiyImages = <DiyImage>[];
  // List _everyUnCheckedDiyImages = [];
  final GlobalKey<ScaffoldState> _globalKey = new GlobalKey<ScaffoldState>();
  String _path = '';

  _getPath() async {
    final Directory _directory = await getApplicationDocumentsDirectory();
    final Directory _imageDirectory =
    await new Directory('${_directory.path}/image/')
        .create(recursive: true);
    _path = _imageDirectory.path;
    print('本次获得路径：${_imageDirectory.path}');
  }

  //遍历数据库初始化_diyProjects数据
  Future<List<Diy>> _getDiyProjects() async {
    _diyProjects = [];
    _diyImages = [];
    _diys = [];
    print('=========开始读取数据库全部数据=========');
    List result = await _database.getDiyProjects();
    print('result.length:${result.length}');
    if (result.length != 0) {
      //根据数据库查询结果把diyProject添加到一个数组中

      result.forEach((diy) => _diyProjects.add(DiyProject.fromMap(diy)));
      print('_diyProjects.length:${_diyProjects.length}');
      //根据diyProject数组的内容查询对应的图片，并添加到一个数组中
      for (int i = 0; i < _diyProjects.length; i++) {
        //重置存放diy图片数据的数组
        _diyImages = <DiyImage>[];
        //根据diyID查询对应图片
        var imageResult = await _database.getImageDatas(_diyProjects[i].id);
        //循环遍历查询结果将查询结果map转换成图片类并加到一个数组中
        imageResult.forEach((imageData) {
          _diyImages.add(DiyImage.fromMap(imageData,_path));
        });
        //将每个diy对应的所有图片数据添加到一个数组中
        _everyDiyImages.add(_diyImages);
      }
      setState(() {
        _diys = List.generate(_diyProjects.length, (index) {
          return new Diy(_diyProjects[index], _everyDiyImages[index]);
        });
      });
      // var diys = List.generate(_diyProjects.length, (index) {
      //   return new Diy(_diyProjects[index], _everyDiyImages[index]);
      // });
      // print('查询数据后的diy数量：${diys.length}');
      // return diys;
    } else
      return null;
  }

  //遍历数据库未结账的_diyProjects数据
  // _getUnCheckedDiyProjects() async {
  //   print('=========开始读取数据库未结账项目数据=========');

  //   List result = await _database.getUnCheckedDiyProjects();
  //   print('${result.length}');
  //   if (result.length != 0) {
  //     //根据数据库查询结果把diyProject添加到一个数组中
  //     result
  //         .forEach((diy) => _unCheckedDiyProjects.add(DiyProject.fromMap(diy)));
  //     //根据diyProject数组的内容查询对应的图片，并添加到一个数组中
  //     for (int i = 0; i < _unCheckedDiyProjects.length; i++) {
  //       //重置存放diy图片数据的数组
  //       _unCheckedDiyImages = <DiyImage>[];
  //       //根据diyID查询对应图片
  //       var imageResult =
  //           await _database.getImageDatas(_unCheckedDiyProjects[i].id);
  //       //循环遍历查询结果将查询结果map转换成图片类并加到一个数组中
  //       imageResult.forEach((imageData) {
  //         _unCheckedDiyImages.add(DiyImage.fromMap(imageData));
  //       });
  //       //将每个diy对应的所有图片数据添加到一个数组中
  //       _everyUnCheckedDiyImages.add(_unCheckedDiyImages);
  //     }
  //     setState(() {
  //       _unCheckedDiys = List.generate(_unCheckedDiyProjects.length, (index) {
  //         return new Diy(
  //             _unCheckedDiyProjects[index], _everyUnCheckedDiyImages[index]);
  //       });
  //     });
  //   } else
  //     _unCheckedDiys = [];
  // }

  //数据初始化
  @override
  void initState() {
    super.initState();
    _getPath();
    _getDiyProjects();
    fluwx.register(appId: 'wx03ec6658decf9ca8');
  }

  //点击底部浮动按钮进入新增页面
  Future _addDiyProject() async {
    var result = await Navigator.of(context).push(
      Theme.of(context).platform == TargetPlatform.iOS
          ? new CupertinoPageRoute(
              fullscreenDialog: true,
              builder: (context) {
                return new DiyAddDialog(
                  db: _database,
                );
              },
            )
          : new MaterialPageRoute(
              fullscreenDialog: true,
              builder: (context) {
                return new DiyAddDialog(
                  db: _database,
                );
              },
            ),
    );
    if (result != null) {
      setState(() {
        _diys.insert(0, result);
      });
    }
    //_getDiyProjects();
    //_getUnCheckedDiyProjects();
  }

  //点击活动卡片进入活动详情页面
  Future _enterDiyItem(int index) async {
    Navigator.of(context)
        .push(new MaterialPageRoute(builder: (BuildContext context) {
      return new DiyItemInfo(
        currentIndex: index,
        diys: _diys,
        db: _database,
      );
    }));
  }

  //删除项目
  Future _deleteDiyProject(Diy diy, int index) async {
    diy.imageDatas.forEach((value) async {
      File _imageFile = new File(value.imageUrl);
      await _imageFile.delete();
    });
    _database
      ..deleteDiyProject(diy.diyProject.id)
      ..deleteImageDatas(diy.diyProject.id).whenComplete(() {
        _globalKey.currentState.showSnackBar(new SnackBar(
          duration: new Duration(seconds: 1),
          content: new Text('"${diy.diyProject.name}" 已删除'),
        ));
      });
    //从当前项目数组中移除该项目，并通知系统重绘
    setState(() {
      _diys.removeAt(index);
    });
    //_getUnCheckedDiyProjects();
  }

  //标记已结算方法进行数据库更新
  _markChecked(Diy diy, int index) async {
    await _database.updateChecked(diy.diyProject);
    setState(
      () {
        _diys[index].diyProject.setIsPaided(
            _diys[index].diyProject.isPaided == true ? false : true);
      },
    );
  }

  //项目卡片右上角菜单按钮底部弹窗
  _showBottomSheet(Diy diy, int indexSelected) {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return new Container(
            height: 248.0,
            child: new Column(
              children: <Widget>[
                new ListTile(
                  leading: new Icon(Xusj.delete),
                  title: new Text('删除'),
                  onTap: () {
                    Navigator.of(context).pop();
                    _alertDialgIsDelete(diy, indexSelected);
                  },
                ),
                new Container(
                  color: Theme.of(context).dividerColor,
                  height: 1.0,
                ),
                new ListTile(
                  leading: !diy.diyProject.isPaided
                      ? Icon(Icons.done_all)
                      : Icon(Icons.highlight_off),
                  title: !diy.diyProject.isPaided
                      ? new Text('标记已结算')
                      : new Text('标记未结算'),
                  onTap: () {
                    Navigator.of(context).pop();
                    _markChecked(diy, indexSelected);
                  },
                ),
                new Container(
                  color: Theme.of(context).dividerColor,
                  height: 1.0,
                ),
                new ListTile(
                  leading: new Icon(Icons.alarm_add),
                  title: new Text('设置收款提醒'),
                  onTap: () {},
                ),
                new Container(
                  color: Theme.of(context).dividerColor,
                  height: 4.0,
                ),
                new ListTile(
                  leading: new Icon(Icons.clear),
                  title: new Text(
                    '取消',
                    style: Theme.of(context)
                        .textTheme
                        .button
                        .copyWith(fontSize: 18.0),
                  ),
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                ),
                new SizedBox(
                  height: 8.0,
                ),
              ],
            ),
          );
        });
  }

  //弹窗对话框确认是否删除
  _alertDialgIsDelete(Diy diy, int indexSelected) {
    showDialog(
      context: context,
      builder: (context) {
        return new AlertDialog(
          title: new Text('确认删除 ${diy.diyProject.name}?'),
          content: new Text('本次删除你将彻底失去我'),
          actions: <Widget>[
            new FlatButton(
              child: new Text('挽留你'),
              onPressed: () => Navigator.pop(context),
            ),
            new FlatButton(
              child: new Text('再见吧'),
              onPressed: () {
                _deleteDiyProject(diy, indexSelected);
                Navigator.pop(context);
              },
            )
          ],
        );
      },
    );
  }

  //底部bottombar的菜单按钮
  Widget _bottomIconButtons(BuildContext context) {
    return new Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        new IconButton(
          icon: new Icon(
            Xusj.search1,
            color: Theme.of(context).accentColor,
          ),
          onPressed: _enterSearchPage,
        ),
        new IconButton(
          icon: new Icon(
            Xusj.bigData,
            color: Theme.of(context).accentColor,
          ),
          onPressed: _enterAnalysisPage,
        )
      ],
    );
  }

  //底部查询按钮点击进入查询页面
  _enterSearchPage() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        fullscreenDialog: true,
        builder: (context) {
          return new DiySearch();
        },
      ),
    );
  }

  //底部统计分析按钮点击进入统计分析页面
  _enterAnalysisPage() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return new DiyDataAnalysis(_database);
        },
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _globalKey,
      appBar: new PreferredSize(
        preferredSize: Theme.of(context).platform == TargetPlatform.iOS
            ? new Size(0.0, 44.0)
            : new Size(0.0, 56.0),
        // child: _searchBar.buildAppBar(context),
        child: new AppBar(
          elevation:
              Theme.of(context).platform == TargetPlatform.iOS ? 1.0 : 4.0,
          title: new GestureDetector(
            onLongPress: () {
              showDialog(
                  context: context,
                  builder: (context) {
                    return new AlertDialog(
                      title: new Text('永远爱你😘老婆！'),
                      actions: <Widget>[
                        new FlatButton(
                          child: new Text('我也爱你'),
                          onPressed: () => Navigator.of(context).pop(),
                        )
                      ],
                    );
                  });
            },
            child: new Text(
              'DIY',
              style: new TextStyle(
                fontSize: 26.0,
                fontFamily: 'Pop',
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          // actions: <Widget>[
          //   new IconButton(
          //     icon: new Icon(Icons.folder_special),
          //     onPressed: () {
          //       Navigator.push(context,
          //           new MaterialPageRoute(builder: (context) {
          //         return new FireStorageTest(
          //           storage: widget.storage,
          //         );
          //       }));
          //     },
          //   ),
          //   new IconButton(
          //     icon: new Icon(Icons.account_balance_wallet),
          //     onPressed: () {
          //       Navigator.push(context,
          //           new MaterialPageRoute(builder: (context) {
          //         return new MyHomePage(
          //           firestore: widget.fireStore,
          //         );
          //       }));
          //     },
          //   ),
          // ],
        ),
      ),
      body: new Scrollbar(
        child: new ListView.builder(
          itemExtent: 288.0,
          itemCount: _diys.length,
          itemBuilder: (context, index) {
            return new GestureDetector(
              onTap: () => _enterDiyItem(index),
              child: new DiyRow(
                diy: _diys[index],
                index: index,
                valueChanged: (index) {
                  _showBottomSheet(_diys[index], index);
                },
              ),
            );
          },
        ),
      ),
      // body: new FutureBuilder<List<Diy>>(
      //   future: _futureBuilderFuture,
      //   builder: (BuildContext context, AsyncSnapshot<List<Diy>> snapshot) {
      //     if (!snapshot.hasData) {
      //       return new Center(
      //         child: new Text('没有活动记录'),
      //       );
      //     } else if(snapshot.connectionState == ConnectionState.waiting){
      //       return new Center(child: new CupertinoActivityIndicator());
      //     }else
      //       {
      //       int _diyCount = snapshot.data.length;
      //       print('_diyCount:${_diyCount}');
      //       return _diyCount == 0
      //           ? new Center(
      //               child: new Text('没有活动记录'),
      //             )
      //           : new Scrollbar(
      //               child: new ListView.builder(
      //                 itemExtent: 288.0,
      //                 itemCount: _diyCount,
      //                 itemBuilder: (context, index) {
      //                   Diy _currentDiy = snapshot.data[index];
      //                   return new GestureDetector(
      //                     onTap: () => _enterDiyItem(index),
      //                     child: new DiyRow(
      //                       diy: _currentDiy,
      //                       index: index,
      //                       valueChanged: (index) {
      //                         _showBottomSheet(_currentDiy, index);
      //                       },
      //                     ),
      //                   );
      //                 },
      //               ),
      //             );
      //     }
      //   },
      // ),
      bottomNavigationBar: new BottomAppBar(
        notchMargin: 6.0,
        shape: DiamondNotchedRectangle(),
        child: _bottomIconButtons(context),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: new FloatingActionButton(
        onPressed: _addDiyProject,
        child: Icon(Icons.add),
        shape: DiamondBorder(),
      ),
    );
  }
}
